package com.rss.view;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.rss.R;
import com.rss.controller.ListAdapter;
import com.rss.controller.RssReader;
import com.rss.controller.XmlParser.Entry;
import com.rss.model.WeatherDataSource;

public class RssReaderActivity extends ListActivity implements
		OnItemClickListener {
	private WeatherDataSource datasource;
	private List<Entry> entries;
	private ProgressDialog mProgressDialog;
	private ListAdapter la;
	private RssReader rr;
	private String path;

	public class DownloadSeed extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			URL url;
			try {
				FileOutputStream fOut = openFileOutput(urls[0],
						MODE_PRIVATE);
				if (urls[0].compareTo("vicweather.xml") == 0)
					url = new URL(
							"http://www.bom.gov.au/fwo/IDZ00059.warnings_vic.xml");
				else
					url = new URL(
							"http://www.bom.gov.au/fwo/IDZ00054.warnings_nsw.xml");
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setDoInput(true);
				conn.connect();
				// this will be useful so that you can show a typical 0-100%
				// progress bar
				int fileLength = conn.getContentLength();

//				InputStream inputstream = new BufferedInputStream(url.openStream());

				InputStream inputstream = conn.getInputStream();
				byte[] buffer = new byte[1024];
				int buffersize = 0;
				long total = 0;

				while ((buffersize = inputstream.read(buffer)) > 0) {
					total += buffersize;
					publishProgress((int) (total * 100 / fileLength));
					fOut.write(buffer, 0, buffersize);
				}

				fOut.flush();
				fOut.close();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);
			mProgressDialog.setProgress(progress[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			fillList();
		}
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		Bundle bundle = getIntent().getExtras();
		String location = bundle.getString("location");
		String name = loadWeather(location);

		// instantiate it within the onCreate method
		mProgressDialog = new ProgressDialog(RssReaderActivity.this);
		mProgressDialog.setMessage("Downloading the Rss feed...");
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setMax(100);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		datasource = new WeatherDataSource(this);
		la = new ListAdapter(this, entries);
		rr = new RssReader(datasource);
		ConnectivityManager connMag = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMag.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			path = name + ".xml";
			new DownloadSeed().execute(path);
			rr.openDB();
			rr.createDB(name, path);

		} else {
			rr.openDB();
			path = datasource.searchWeather(name);
			new AlertDialog.Builder(RssReaderActivity.this).
			setTitle(R.string.NETWORK_ERROR_TITLE)
			.setMessage(R.string.NETWORK_ERROR_CONTENT)
			.setPositiveButton(R.string.Confirm_string, new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			    	  fillList();
			    } }).show();
			Log.e(CONNECTIVITY_SERVICE, "No internet!");
		}
			
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String link = entries.get((int) id).link;
		Uri uri = Uri.parse(link);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
		Toast.makeText(getApplicationContext(),
				link.subSequence(0, link.length()), Toast.LENGTH_LONG).show();

	}

	private String loadWeather(String location) {
		if (location.compareTo("vic") == 0) {
			return "vicweather";
		} else {
			return "nswweather";
		}
	}
	
	private void fillList(){
		la.readXML(path);
		List<String> titles = la.getTitles();
		entries = la.getEntries();
		setListAdapter(new ArrayAdapter<String>(this, R.layout.reader,
				(String[]) titles.toArray(new String[0])));
		ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(this);
		rr.destroy();
	}

	

}